package com.shanzmoo.db.common.config;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.shanzmoo.db.common.inface.UserComponentInface;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
/**
 * 自定义填充公共 name 字段
 * @author fs
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class DateMetaObjectHandler implements MetaObjectHandler {
    private final static String CREATE_TIME = "createTime";
    private final static String UPDATE_TIME = "updateTime";
    private final static String CREATE_USER = "createUser";
    private final static String DELETED = "deleted";

    /**
     * 插入填充,强制填充
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        LocalDateTime now = LocalDateTime.now();
        if(metaObject.hasSetter(CREATE_TIME)) {
            this.setFieldValByName(CREATE_TIME, now, metaObject);
        }
        if(metaObject.hasSetter(UPDATE_TIME)) {
            this.setFieldValByName(UPDATE_TIME, now, metaObject);
        }
        if(metaObject.hasSetter(CREATE_USER)) {
            try{
                UserComponentInface uc = SpringUtil.getBean(UserComponentInface.class);
                if(uc != null){
                    Integer userId = uc.getUserId();
                    if(userId != null){
                        this.setFieldValByName(CREATE_USER, userId, metaObject);
                    }
                }
            }catch (Exception e){
                log.error("读取UserComponentInface实现失败");
            }
        }
        if(metaObject.hasSetter(DELETED)) {
            this.setFieldValByName(DELETED, false, metaObject);
        }
    }

    /**
     * 更新填充,强制填充
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        LocalDateTime now = LocalDateTime.now();
        if(metaObject.hasSetter(UPDATE_TIME)) {
            this.setFieldValByName(UPDATE_TIME, now, metaObject);
        }
    }
}
